package com.tanhua.dubbo.api;

import com.mongodb.client.result.DeleteResult;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
@DubboService
public class FriendApiImpl implements FriendApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    //添加好友
    @Override
    public void save(Long userId, Long friendId) {
        //1、保存自己的好友数据
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("frinedId").is(friendId));
       if (!mongoTemplate.exists(query1, Friend.class)){
           //不存在保存
           Friend friend1 = new Friend();
           friend1.setUserId(userId);
           friend1.setFriendId(friendId);
           friend1.setCreated(System.currentTimeMillis());
           mongoTemplate.save(friend1);
       }
        //2、保存好友的数据
        Query query2 = Query.query(Criteria.where("userId").is(friendId).and("frinedId").is(userId));
        if (!mongoTemplate.exists(query1, Friend.class)){
            //不存在保存
            Friend friend1 = new Friend();
            friend1.setUserId(friendId);
            friend1.setFriendId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
    }

   //分页查询联系人列表
    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId)).skip((page-1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        return list;
    }

    //删除好友
    @Override
    public void remove(Long likeUserId, Long userId) {
        //构建条件
        Criteria criteria = Criteria.where("friendId").is(likeUserId).and("userId").is(userId);
        Query query = Query.query(criteria);
        //然后进行删除操作
        mongoTemplate.remove(query, Friend.class);
        Criteria criteria1 = Criteria.where("friendId").is(userId).and("userId").is(likeUserId);
        mongoTemplate.remove(Query.query(criteria1),Friend.class);
    }


    /**
     * 查询互相喜欢，也就是查询好友数
     * @param userId
     * @return
     */
    @Override
    public Integer findEachLoveCount(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        return list.size();
    }
}
